import os
import time
from datetime import datetime

import fitz  # PyMuPDF
from openpyxl import load_workbook

startTime = time.time()

# 打开Excel文件
excel_file = "input_excel/" + '1.xlsx'
wb = load_workbook(excel_file)

# 获取特定的工作表，这里假设工作表名为"MySheet"
sheet_name = 'MySheet'
sheet = wb[sheet_name]

current_directory = os.getcwd() + "/input_pdf"
# 全局字体
# 创建一个字体对象以计算文本尺寸
ffile = "simsun.ttc"  # chinese font, light version
font = fitz.Font(fontfile=ffile)
# 使用os.walk遍历当前目录及其所有子目录
for root, dirs, files in os.walk(current_directory):
    for name in files:
        # 获取文件的完整路径
        full_path = os.path.join(root, name)
        print(f"开始处理文件: {full_path}")
        # 打开PDF文件
        pdf_document = fitz.open(full_path)

        # 遍历每一页并添加文本
        for page_number in range(len(pdf_document)):
            update_time = time.time()
            # 判断文本是否为空
            text = sheet.cell(row=page_number + 2, column=2).value
            font_size = sheet.cell(row=page_number + 2, column=3).value
            bottom_margin_cm = sheet.cell(row=page_number + 2, column=4).value
            if text is None or font_size is None or bottom_margin_cm is None:
                continue
            bottom_margin_cm = float(bottom_margin_cm)
            # 转换底部边距为像素
            bottom_margin_px = bottom_margin_cm / 2.54 * 72  # 1 inch = 2.54 cm, 1 inch = 72 points
            text_height = font_size
            page = pdf_document[page_number]
            page.insert_font(fontname="f0", fontfile=ffile)

            margin = 1 * 72 / 2.54  # 左右页边距
            page_width = page.rect.width
            page_height = page.rect.height
            max_width = page_width - margin * 2
            # 自动换行
            line = ""
            row = 1
            for word in text:
                if font.text_length(line, font_size) <= max_width:
                    if line:
                        line += word
                    else:
                        line = word
                else:
                    text_length = font.text_length(line, font_size)
                    x = (page_width - text_length) / 2
                    y = page_height - bottom_margin_px - (text_height * row)
                    # 插入文本到页面
                    page.insert_text((x, y), line, fontsize=font_size, fontname="f0")
                    line = word
                    row = row - 1

            text_length = font.text_length(line, font_size)
            x = (page_width - text_length) / 2
            y = page_height - bottom_margin_px - (text_height * row)
            # 插入文本到页面
            page.insert_text((x, y), line, fontsize=font_size, fontname="f0")
            print(f"第{page_number + 1}页完成，花费时间:{time.time() - update_time}")

        # 保存修改后的PDF文件
        time_str = datetime.now().strftime("%H%M%S")
        new_filename = f"{name.rsplit('.', 1)[0]}_{time_str}.{name.rsplit('.', 1)[1]}"
        print("开始保存pdf...")
        output_pdf_path = "output_pdf/" + new_filename
        pdf_document.save(output_pdf_path)

print("总共花费时间：", time.time() - startTime)
